﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Windows.Forms;

namespace DevToolsRepo
{
	public class ToolRepository
	{
		public List<ToolInfo> Tools { get; set; }
		public List<TagInfo> Tags { get; set; }

		#region [ Instance ]
		private static ToolRepository _instance;
		public static ToolRepository Instance
		{
			get
			{
				if (_instance == null)
					_instance = new ToolRepository();
				return _instance;
			}
		} 
		#endregion

		#region [ FilePath ]
		private const string FILENAME = "tools.xml";
		[XmlIgnore]
		public string SaveFilePath
		{
			get { return Path.Combine(Application.StartupPath, FILENAME); }
		}
		#endregion

		#region [ CTOR ]
		public ToolRepository()
		{
			Tools = new List<ToolInfo>();
			Tags = new List<TagInfo>();
		}
		#endregion

		#region [ Save ]
		public void Save()
		{
			var filePath = SaveFilePath;
			var writer = new XmlSerializer(this.GetType());
			using (var file = new StreamWriter(filePath))
			{
				try
				{
					writer.Serialize(file, this);
				}
				finally
				{
					file.Close();
				}
			}
		}
		#endregion

		#region [ Load ]
		public void Load()
		{
			var filePath = SaveFilePath;
			if (File.Exists(filePath))
			{
				var reader = new XmlSerializer(this.GetType());
				using (var file = new StreamReader(filePath))
				{
					try
					{
						var repo = reader.Deserialize(file) as ToolRepository;
						this.Tools = repo.Tools;
						this.Tags = repo.Tags;
					}
					finally
					{
						file.Close();
					}
				}
			}
		}
		#endregion
	}
}
